<?php


namespace app\api\service;

use app\api\model\Consumer as ConsumerModel;
use app\lib\enum\ScopeEnum;
use app\lib\exception\TokenException;
use app\lib\exception\WeChatException;

class ConsumerToken extends Token
{

    // 返回带有token值得用户手机号码
    public function get($wxResult)
    {
        $phone = $wxResult['phoneNumber'];
        $info = ConsumerModel::getByPhone($phone);

        if($info){
            return $this->grantToken($wxResult ,$info);
        }else{
            throw new WeChatException([
                'msg' => '用户不存在',
                'errorCode' => 400
            ]);
        }
    }

    private function grantToken($wxResult ,$info)
    {
        $uid = $info['id'];
        $cacheValue = $this->prepareCachedValue($wxResult, $uid);
        $token = $this->saveToCache($cacheValue);
        $wxResult["token"] = $token;

        return $wxResult;
    }

    private function prepareCachedValue($wxResult, $uid)
    {
        $cacheValue = $wxResult;
        $cacheValue['uid'] = $uid;
        // 权限
        $cacheValue['scope'] = ScopeEnum::User;

        return $cacheValue;
    }

    private function saveToCache($cacheValue)
    {
        $key = self::generateToken();
        $value = json_encode($cacheValue);
        $expire_in = config('setting.token_expire_in');
        $request = cache($key, $value, $expire_in);

        if (!$request){
            throw new TokenException([
                'msg' => '服务器异常',
                'errorCode' => 10005
            ]);
        }

        return $key;
    }
}